package org.wskyh.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

public class TCPClient {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("localhost", 8888);

        // 发送消息
        new Thread(() -> {
            // 反复发送消息
            String request;
            Scanner scanner = new Scanner(System.in);
            try {
                OutputStream outputStream = socket.getOutputStream();
                do {
                    request = scanner.next();
                    outputStream.write(request.getBytes());
                } while (!"exit".equals(request));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 接收信息
        new Thread(() -> {
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes;
                do {
                    bytes = new byte[1024];
                    inputStream.read(bytes);
                    System.out.println("服务端：" + new String(bytes));
                } while (!"exit".equals(new String(Arrays.copyOf(bytes, 4))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}